//
//  HMComposeViewController.swift
//  Weibo
//
//  Created by Apple on 2017/7/16.
//  Copyright © 2017年 KY. All rights reserved.
//

import UIKit
import SVProgressHUD

//  撰写视图控制器
class HMComposeViewController: UIViewController {
    
    //  MARK:   --懒加载控件
    private lazy var titleLabel: UILabel = {
        let label = UILabel(fontSize: 17, textColor: UIColor.darkGray)
        if let name = HMUserAccountViewModel.sharedUserAccount.userAccount?.name {
            let title = "发微博\n" + name
            
            let attributedText: NSMutableAttributedString = NSMutableAttributedString(string: title)
            let range = (title as NSString).range(of: name)
            attributedText.addAttributes([NSForegroundColorAttributeName: UIColor.orange, NSFontAttributeName: UIFont.systemFont(ofSize: 12)], range: range)
            label.attributedText = attributedText
            
        } else {
            label.text = "发微博"
        }
        label.textAlignment = .center
        label.numberOfLines = 0
        label.sizeToFit()
        return label
    }()
    
    fileprivate lazy var textView: HMTextView = {
        let textView = HMTextView()
        //  不显示纠错提示
//        textView.autocorrectionType = .no
        textView.delegate = self
        textView.placeHolder = "听说下雨天音乐和辣条更配哟~听说下雨天音乐和辣条更配哟~听说下雨天音乐和辣条更配哟~听说下雨天音乐和辣条更配哟~"
        textView.font = UIFont.systemFont(ofSize: 13)
        textView.alwaysBounceVertical = true
        return textView
    }()
    
    private lazy var sendButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: #selector(sendAction), for: .touchUpInside)
        button.setTitle("发送", for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        button.setBackgroundImage(UIImage(named: "common_button_orange"), for: .normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: .highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_disable"), for: .disabled)
        button.setTitleColor(UIColor.white, for: .normal)
        button.setTitleColor(UIColor.gray, for: .disabled)
        button.size = CGSize(width: 45, height: 35)
        return button
    }()
    
    fileprivate lazy var toolBar: HMComposeToolBar = HMComposeToolBar()
    //  配图
    fileprivate lazy var pictureView: HMComposePictureView = {
        let pictureView = HMComposePictureView()
        pictureView.backgroundColor = self.textView.backgroundColor
        return pictureView
    }()
    
    //  表情键盘
    fileprivate lazy var emoticonKeyBoard: HMEmoticonKeyBoard = {
        let keyboard = HMEmoticonKeyBoard(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: ScreenWidth, height: 216)))
        return keyboard
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        setupUI()
    }
    
    private func setupUI() {
        //  监听键盘frame改变的通知
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardFrameChange(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        //  监听表情按钮点击的通知
        NotificationCenter.default.addObserver(self, selector: #selector(clickEmoticonButtonAction(noti:)), name: NSNotification.Name(ClickEmoticonButonNotificationName), object: nil)
        setupNavUI()
        view.addSubview(textView)
        textView.addSubview(pictureView)
        view.addSubview(toolBar)
        textView.snp.makeConstraints { (make) in
            make.top.leading.trailing.equalTo(view)
            make.bottom.equalTo(view)
        }
        
        pictureView.snp.makeConstraints { (make) in
            make.centerX.equalTo(textView)
            make.top.equalTo(textView).offset(100)
            make.width.equalTo(textView).offset(-2 * HomeCellMargin)
            make.height.equalTo(textView.snp.width).offset(-2 * HomeCellMargin)
        }
        
        toolBar.snp.makeConstraints { (make) in
            make.bottom.equalTo(view)
            make.leading.trailing.equalTo(textView)
            make.height.equalTo(35)
        }
        
        toolBar.callBack = { [unowned self] (type) in
            switch type {
            case .picture:
                print("图片")
                self.didSelectedPicture()
            case .mention:
                print("@")
            case .trend:
                print("#")
            case .emoticon:
                print("表情")
                self.didSelectedEmoticon()
            case .add:
                print("加号")
            }
        
        }
        pictureView.callBack = { [unowned self] in
            self.didSelectedPicture()
        }
    }

    //  设置导航栏按钮
    private func setupNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
        navigationItem.titleView = titleLabel
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        navigationItem.rightBarButtonItem?.isEnabled = false
    }
    
    //  MARK:   --取消事件点击
    @objc private func cancelAction() {
        self.view.endEditing(true)
        dismiss(animated: true, completion: nil)
    }
    
    //  MARK:   --发送微博事件
    @objc private func sendAction() {
        
        
//        let text = textView.text!
        let text = textView.emoticonText
        print(text)
        let accessToken = HMUserAccountViewModel.sharedUserAccount.accessToken!
        if pictureView.images.count > 0 {
            let image = pictureView.images.first!
            HMNetworkTools.sharedTools.sendWeibo(access_token: accessToken, status: text, pic: image, callBack: { (response, error) in
                if error != nil {
                    print("error: \(error!)")
                    SVProgressHUD.showError(withStatus: "发送失败")
                    return
                }
                SVProgressHUD.showSuccess(withStatus: "发送成功")
            })
        } else {
            HMNetworkTools.sharedTools.sendWeibo(access_token: accessToken, status: text) { (response, error) in
                if error != nil {
                    print("error: \(error!)")
                    SVProgressHUD.showError(withStatus: "发送失败")
                    return
                }
                SVProgressHUD.showSuccess(withStatus: "发送成功")
            }
        }
        
    }
    
    //  MARK:   --键盘frame的改变通知方法
    @objc private func keyboardFrameChange(noti: Notification) {
    
        let keyBoardFrame = noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! CGRect
        print(keyBoardFrame)
        
        toolBar.snp.updateConstraints { (make) in
            make.bottom.equalTo(view).offset(keyBoardFrame.origin.y - ScreenHeight)
        }
        
        UIView.animate(withDuration: 0.25) { 
            self.view.layoutIfNeeded()
        }
        
    }
    
    //  MARK:   --监听表情点击的通知
    @objc private func clickEmoticonButtonAction(noti: Notification) {
        let emoticon = noti.object as! HMEmoticon
        textView.insertEmoticon(emoticon: emoticon)
        
        //  保存最近表情
        HMEmoticonTools.sharedTools.saveRecentEmoticon(emoticon: emoticon) { 
            //  重新加载最近这组表情
            self.emoticonKeyBoard.reloadRecentData()
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    

}

//  MARK:   --toolBar按钮点击事件处理
extension HMComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    //  点击表情按钮事件处理
    func didSelectedEmoticon() {
        if textView.inputView == nil {
            //  系统键盘进入表情键盘
            textView.inputView = emoticonKeyBoard
            toolBar.switchButtonIcon(isEmoticon: true)
        } else {
            //  表情键盘进入系统键盘
            textView.inputView = nil
            toolBar.switchButtonIcon(isEmoticon: false)
        }
        
        textView.becomeFirstResponder()
        textView.reloadInputViews()
        
    }
    
    func didSelectedPicture() {
        let imagePicCtr = UIImagePickerController()
        imagePicCtr.delegate = self
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            imagePicCtr.sourceType = .camera
        } else {
            imagePicCtr.sourceType = .photoLibrary
        }
        self.present(imagePicCtr, animated: true, completion: nil)
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        let currentImage = scaleImage(scaleWidth: 80, image: image)
        pictureView.addImage(image: currentImage)
        picker.dismiss(animated: true, completion: nil)
    }
    
    //  等比压缩图片
    func scaleImage(scaleWidth: CGFloat, image: UIImage) -> UIImage {
        let scaleHeight = scaleWidth / image.size.width * image.size.height
        let scaleSize = CGSize(width: scaleWidth, height: scaleHeight)
        UIGraphicsBeginImageContext(scaleSize)
        //  渲染到指定区域
        image.draw(in: CGRect(origin: CGPoint.zero, size: scaleSize))
        let currentImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return currentImage!
    }
    
    
}


//  MARK:   --UITextViewDelegate
extension HMComposeViewController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
}
